//
//  WBOAuthViewController.swift
//  Weibo
//
//  Created by apple on 2016/12/6.
//  Copyright © 2016年 yanjun. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {

    
    private lazy var webView = UIWebView()
    
    
    override func loadView() {
        view = webView
        
        view.backgroundColor = UIColor.white
        
        webView.scrollView.isScrollEnabled = false
        
        webView.delegate = self
        
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAPPKey)&redirect_uri=\(WBRedirectURI)"
        
        guard let url = URL(string: urlString) else {
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
        
    }
    
    
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }


}


extension WBOAuthViewController : UIWebViewDelegate
{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
            
            return true
            
        }
        
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消授权")
            close()
            return false
        }
        
        // 获取授权码
        let code =  request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        // 使用授权码获取 AccessToken
        WBNetworkManager.shared().loadAccessToken(code: code, completion: { (isSuccess) in
        
            if isSuccess {
                SVProgressHUD.showSuccess(withStatus: "登录成功")

                self.close()
                
            }else{
                SVProgressHUD.showError(withStatus: "网络请求失败")
                
                // 发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            }
        
        })
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
     
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
